﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PubSubLite.Messaging;

namespace PubSubLite
{
    /// <summary>
    /// This class represents a subscription.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class Subscription<T> : ISubscription<T>
    {

        public Subscription(ISubscriber<T> subscriber)
        {
            if (subscriber == null)
            {
                throw new ArgumentNullException("subscriber cannot be null");
            }
            _subscriber = subscriber;
            ID = Guid.NewGuid();
            Address = new Address();
        }

        private ISubscriber<T> _subscriber;
        private Func<IMessage<T>, bool> _filterFunc;

        public Address Address
        {
            get;
            private set;
        }

        public Guid ID
        {
            get;
            private set;
        }

        Type ISubscriptionBase.Type
        {
            get { return typeof(T); }
        }

        /// <summary>
        /// <para>
        /// Any Func can be supplied as a lambda expression to filter out messages for the current subscription.
        /// </para>
        /// <para>
        /// PubSubLite.Bus.Subscripe&lt;MyMessage&gt;(this).ApplyFilter(x => x.Category.StartsWith("A"));
        /// </para>
        /// </summary>
        /// <param name="filterFunc"></param>
        /// <returns></returns>
        ISubscription<T> ISubscription<T>.ApplyFilter(Func<IMessage<T>, bool> filterFunc)
        {
            _filterFunc = filterFunc;
            return this;
        }

        private bool FilterMatches(IMessage<T> message)
        {
            if (_filterFunc == default(Func<IMessage<T>, bool>))
            {
                return true;
            }
            return _filterFunc.Invoke(message);
        }

        internal void Notify(IMessage<T> message)
        {
            if (FilterMatches(message) && _subscriber != null)
            {
                _subscriber.HandleMessage(message);
            }
        }

        void ISubscription<T>.Notify(IMessage<T> message)
        {
            Notify(message);
        }

        Guid ISubscriptionBase.ID
        {
            get { return ID; }
        }

        object ISubscriptionBase.Subscriber
        {
            get { return _subscriber; }
        }
    }
}
